using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

/// <summary>
/// Summary description for ImageUpload
/// </summary>
public class ImageUpload
{
	public ImageUpload()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    // function Upload Image
    public string UploadImage(HttpPostedFile postedImage, string imageDirectory, int targetWidth, int targetHeight, string prefix)
    {
        string fileName = Utility.GetFullName(postedImage.FileName);
        string serverImageDir = HttpContext.Current.Server.MapPath(imageDirectory);

        //image Attributes and Properties to be set
        int ThumbWidth = 0;
        int ThumbHeight = 0;

        ImageCodecInfo upiImageCodecInfo = null;
        Encoder upiEncoder = null;
        EncoderParameter upiEncoderParameter = null;
        EncoderParameters upiEncoderParameters = null;

        using (Bitmap originalImage = new Bitmap(postedImage.InputStream, false))
        {

            //No difference of image quality has been noticed between
            //75L and 100L while testing this code. BUT the file size
            //triples with the setting at 100L.  Keep these settings
            //for optimal performance.

            if (originalImage.RawFormat.Equals(ImageFormat.Jpeg))
            {
                upiImageCodecInfo = GetEncoderInfo("image/jpeg");
                upiEncoder = Encoder.Quality;
                upiEncoderParameters = new EncoderParameters(1);
                upiEncoderParameter = new EncoderParameter(upiEncoder, 75L);
                upiEncoderParameters.Param[0] = upiEncoderParameter;
            }

            if (originalImage.RawFormat.Equals(ImageFormat.Gif))
            {
                upiImageCodecInfo = GetEncoderInfo("image/gif");
                upiEncoder = Encoder.Quality;
                upiEncoderParameters = new EncoderParameters(1);
                upiEncoderParameter = new EncoderParameter(upiEncoder, 75L);
                upiEncoderParameters.Param[0] = upiEncoderParameter;
            }

            int width = originalImage.Width;
            int height = originalImage.Height;

            if (width > targetWidth || height > targetHeight)
            {
                //Resize the image proportionally.
                double changeRatio;
                if (width > targetWidth && height > targetHeight)
                {
                    if (height < width)
                    { //landscape image
                        changeRatio = (double)targetWidth / (double)width;
                    }                        
                    else if (height == width)
                    {
                        //Thay doi:
                        changeRatio = (double)targetWidth / (double)width;
                    }
                    else
                    { // portrait/square image
                        changeRatio = (double)targetHeight / (double)height;
                    }
                }
                else if (width > targetWidth && height <= targetHeight)
                {
                    changeRatio = (double)targetWidth / (double)width;
                }
                else
                {
                    changeRatio = (double)targetHeight / (double)height;
                }

                ThumbHeight = (int)(height * changeRatio);
                ThumbWidth = (int)(width * changeRatio);

                if (ThumbHeight <= 0) ThumbHeight = 1;
                if (ThumbWidth <= 0) ThumbWidth = 1;

                // CREATE A BITMAP INSTEAD OF GETTING THUMBNAIL DIRECTLY FROM STREAM,
                // THIS IMPROVES THUMBNAIL IMAGE QUALITY A LOT
                Bitmap tBitmap = new Bitmap(originalImage, width, height);
                System.Drawing.Image tImage = tBitmap.GetThumbnailImage(ThumbWidth, ThumbHeight, null, System.IntPtr.Zero);
                

                if (upiImageCodecInfo != null && upiEncoderParameters != null) // gif or jpeg file
                {
                      tImage.Save((serverImageDir + prefix + fileName), upiImageCodecInfo, upiEncoderParameters);
                }               
                else
                { // other image type --> save as JPEG
                    fileName = Utility.GetName(postedImage.FileName) + ".jpg";
                    tImage.Save((serverImageDir + prefix + fileName), System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                
                // clean up
                tBitmap.Dispose();
                tImage.Dispose();
            }
            else
            {
                // JPEG or GIF
                if (upiImageCodecInfo != null && upiEncoderParameters != null)
                    //IF THE IMAGE DOES NOT NEED RESIZING, JUST SAVE IT AS ORIGINAL
                    postedImage.SaveAs(serverImageDir + prefix + fileName);
                else
                { // BMP or PNG --> save as JPEG however
                    Bitmap tBitmap = new Bitmap(originalImage, width, height);
                    System.Drawing.Image tImage = tBitmap.GetThumbnailImage(width, height, null, System.IntPtr.Zero);
                    fileName = Utility.GetName(postedImage.FileName) + ".jpg";
                    tImage.Save(serverImageDir + prefix + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

                    // clean up
                    tBitmap.Dispose();
                    tImage.Dispose();
                }
            }

            return fileName;
        }
    }

    private ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();

        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }

        return null;
    }



}
